﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace EffiProz.Core.Lib
{
    public class LineGroupReader
    {
        private static String[] defaultContinuations = new String[] {
        " ", "*"
    };
        private static String[] defaultIgnoredStarts = new String[] { "--" };
        const String LS = "\n";

        //
        StreamReader reader;
        String nextStartLine = null;
        int startLineNumber = 0;
        int nextStartLineNumber = 0;

        //
        String[] sectionContinuations;
        String[] sectionStarts;
        String[] ignoredStarts;

        /**
         * Default constructor for TestUtil usage.
         * Sections start at lines beginning with any non-space character.
         * SQL comment lines are ignored.
         */
        public LineGroupReader(StreamReader reader)
        {

            this.sectionContinuations = defaultContinuations;
            this.sectionStarts = new string[0];
            this.ignoredStarts = defaultIgnoredStarts;
            this.reader = reader;

            try
            {
                getSection();
            }
            catch (Exception )
            { }
        }

        /**
         * Constructor for sections starting with specified strings.
         */
        public LineGroupReader(StreamReader reader, String[] sectionStarts)
        {

            this.sectionStarts = sectionStarts;
            this.sectionContinuations = new string[0];
            this.ignoredStarts = new string[0];
            this.reader = reader;

            try
            {
                getSection();
            }
            catch (Exception ) { }
        }

        public EfzArrayList getSection()
        {

            String line;
            EfzArrayList list = new EfzArrayList();

            if (nextStartLine != null)
            {
                list.add(nextStartLine);

                startLineNumber = nextStartLineNumber;
            }

            int lineNo = 1;
            while (true)
            {
                bool newSection = false;

                line = null;

                try
                {
                    line = reader.ReadLine();
                }
                catch (Exception ) { }
                lineNo++;

                if (line == null)
                {
                    nextStartLine = null;

                    return list;
                }

                line = line.Substring(
                    0, StringUtil.rightTrimSize(line));

                //if the line is blank or a comment, then ignore it
                if (line.Length == 0 || isIgnoredLine(line))
                {
                    continue;
                }

                if (isNewSectionLine(line))
                {
                    newSection = true;
                }

                if (newSection)
                {
                    nextStartLine = line;
                    nextStartLineNumber = lineNo;

                    return list;
                }

                list.add(line);
            }
        }

        /**
         * Returns a map/list which contains the first line of each line group
         * as key and the rest of the lines as a String value.
         */
        public HashMappedList getAsMap()
        {

            HashMappedList map = new HashMappedList();

            while (true)
            {
                EfzArrayList list = getSection();

                if (list.size() < 1)
                {
                    break;
                }

                String key = (String)list.get(0);
                String value = LineGroupReader.convertToString(list, 1);

                map.put(key, value);
            }

            return map;
        }

        private bool isNewSectionLine(String line)
        {

            if (sectionStarts.Length == 0)
            {
                for (int i = 0; i < sectionContinuations.Length; i++)
                {
                    if (line.StartsWith(sectionContinuations[i]))
                    {
                        return false;
                    }
                }

                return true;
            }
            else
            {
                for (int i = 0; i < sectionStarts.Length; i++)
                {
                    if (line.StartsWith(sectionStarts[i]))
                    {
                        return true;
                    }
                }

                return false;
            }
        }

        private bool isIgnoredLine(String line)
        {

            for (int i = 0; i < ignoredStarts.Length; i++)
            {
                if (line.StartsWith(ignoredStarts[i]))
                {
                    return true;
                }
            }

            return false;
        }

        public int getStartLineNumber()
        {
            return startLineNumber;
        }

        public void close()
        {
            try
            {
                reader.Close();
            }
            catch (Exception ) { }
        }

        public static String convertToString(EfzArrayList list, int offset)
        {

            StringBuilder sb = new StringBuilder();

            for (int i = offset; i < list.size(); i++)
            {
                sb.Append(list.get(i)).Append(LS);
            }

            return sb.ToString();
        }
    }
}
